// 用户管理API接口
import type { User } from '../types/user';
import { http, getAPI_BASE_URL_SYNC } from '../lib/http-client';
import { shouldUseMockServer } from '../config/app.config';
import { userData } from '../data/userData';

// 用户API基础路径
const USER_API_BASE = `${getAPI_BASE_URL_SYNC()}/users`;
// API请求参数接口
export interface GetUsersParams {
  page?: number;
  pageSize?: number;
  search?: string;
  role?: string;
  status?: number;
}

// API响应接口
export interface ApiResponse<T> {
  data: T;
  total: number;
  success: boolean;
  message?: string;
}

// 后端API响应格式（根据实际后端API调整）
interface BackendApiResponse<T> {
  code: number;
  message: string;
  data: T;
  total?: number;
  success?: boolean;
}

// 用户列表响应格式
interface UserListResponse {
  users: User[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// 用户模拟API实现
const mockUserApi = {
  async getUsers(params: GetUsersParams = {}): Promise<ApiResponse<User[]>> {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const { page = 1, pageSize = 10, search, role, status } = params;
    
    // 过滤数据
    let filteredData = [...userData];
    
    if (search) {
      filteredData = filteredData.filter(user => 
        user.username.toLowerCase().includes(search.toLowerCase()) ||
        user.email.toLowerCase().includes(search.toLowerCase()) ||
        user.name?.toLowerCase().includes(search.toLowerCase())
      );
    }
    
    if (role) {
      filteredData = filteredData.filter(user => user.role === role);
    }
    
    if (status !== undefined) {
      filteredData = filteredData.filter(user => user.status === status);
    }
    
    // 分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);
    
    return {
      data: paginatedData,
      total: filteredData.length,
      success: true,
      message: '获取用户列表成功'
    };
  },

  async createUser(userDataParam: Partial<User>): Promise<ApiResponse<User>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const newUser: User = {
      id: Date.now(),
      username: userDataParam.username || '',
      email: userDataParam.email || '',
      name: userDataParam.name || '',
      role: userDataParam.role || 'user',
      status: userDataParam.status || 1,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };
    
    userData.push(newUser);
    
    return {
      data: newUser,
      total: 1,
      success: true,
      message: '用户创建成功'
    };
  },

  async updateUser(userId: number, userDataParam: Partial<User>): Promise<ApiResponse<User>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = userData.findIndex(user => user.id === userId);
    if (index === -1) {
      throw new Error('用户不存在');
    }
    
    userData[index] = { ...userData[index], ...userDataParam, updatedAt: new Date().toISOString() };
    
    return {
      data: userData[index],
      total: 1,
      success: true,
      message: '用户信息更新成功'
    };
  },

  async deleteUser(userId: number): Promise<ApiResponse<boolean>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = userData.findIndex(user => user.id === userId);
    if (index === -1) {
      throw new Error('用户不存在');
    }
    
    userData.splice(index, 1);
    
    return {
      data: true,
      total: 1,
      success: true,
      message: '用户删除成功'
    };
  },

  async toggleUserStatus(userId: number, status: number): Promise<ApiResponse<User>> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const index = userData.findIndex(user => user.id === userId);
    if (index === -1) {
      throw new Error('用户不存在');
    }
    
    userData[index].status = status;
    userData[index].updatedAt = new Date().toISOString();
    
    return {
      data: userData[index],
      total: 1,
      success: true,
      message: `用户状态已${status === 1 ? '启用' : '禁用'}`
    };
  }
};

export const userApi = {
  // 获取用户列表（支持分页、搜索、筛选）
  async getUsers(params: GetUsersParams = {}): Promise<ApiResponse<User[]>> {
    if (shouldUseMockServer()) {
      return mockUserApi.getUsers(params);
    }
    try {
      const { page = 1, pageSize = 10, search, role, status } = params;
      
      // 构建查询参数
      const queryParams = new URLSearchParams({
        page: page.toString(),
        pageSize: pageSize.toString()
      });
      
      if (search) queryParams.append('search', search);
      if (role) queryParams.append('role', role);
      if (status !== undefined) queryParams.append('status', status.toString());
      
      const url = `${USER_API_BASE}?${queryParams.toString()}`;
      
      // 发送GET请求
      const response = await http.get<BackendApiResponse<UserListResponse>>(url);
      
      // 根据后端API响应格式调整
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        // 直接返回后端数据，不需要再次解包
        const userList = backendData.data as UserListResponse;
        return {
          data: userList.users || [],
          total: userList.total || 0,
          success: true,
          message: backendData.message || '获取用户列表成功'
        };
      } else {
        throw new Error(backendData.message || '获取用户列表失败');
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      
      // 如果后端API不可用，返回空数据（开发阶段）
      return {
        data: [],
        total: 0,
        success: false,
        message: error instanceof Error ? error.message : '获取用户列表失败'
      };
    }
  },

  // 创建用户
  async createUser(userData: Partial<User>): Promise<ApiResponse<User>> {
    if (shouldUseMockServer()) {
      return mockUserApi.createUser(userData);
    }
    try {
      // 发送POST请求
      const response = await http.post<BackendApiResponse<User>>(USER_API_BASE, userData);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '用户创建成功'
        };
      } else {
        throw new Error(backendData.message || '创建用户失败');
      }
    } catch (error) {
      console.error('创建用户失败:', error);
      throw new Error(error instanceof Error ? error.message : '创建用户失败');
    }
  },

  // 更新用户
  async updateUser(userId: number, userData: Partial<User>): Promise<ApiResponse<User>> {
    if (shouldUseMockServer()) {
      return mockUserApi.updateUser(userId, userData);
    }
    try {
      const url = `${USER_API_BASE}/${userId}`;
      
      // 发送PUT请求
      const response = await http.put<BackendApiResponse<User>>(url, userData);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || '用户信息更新成功'
        };
      } else {
        throw new Error(backendData.message || '更新用户失败');
      }
    } catch (error) {
      console.error('更新用户失败:', error);
      throw new Error(error instanceof Error ? error.message : '更新用户失败');
    }
  },

  // 删除用户
  async deleteUser(userId: number): Promise<ApiResponse<boolean>> {
    if (shouldUseMockServer()) {
      return mockUserApi.deleteUser(userId);
    }
    try {
      const url = `${USER_API_BASE}/${userId}`;
      
      // 发送DELETE请求
      const response = await http.delete<BackendApiResponse<boolean>>(url);
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: true,
          total: 1,
          success: true,
          message: backendData.message || '用户删除成功'
        };
      } else {
        throw new Error(backendData.message || '删除用户失败');
      }
    } catch (error) {
      console.error('删除用户失败:', error);
      throw new Error(error instanceof Error ? error.message : '删除用户失败');
    }
  },

  // 切换用户状态
  async toggleUserStatus(userId: number, status: number): Promise<ApiResponse<User>> {
    if (shouldUseMockServer()) {
      return mockUserApi.toggleUserStatus(userId, status);
    }
    try {
      const url = `${USER_API_BASE}/${userId}/status`;
      
      // 发送PATCH请求更新状态
      const response = await http.patch<BackendApiResponse<User>>(url, { status });
      
      const backendData = response.data;
      
      if (backendData.code === 200 || backendData.success) {
        return {
          data: backendData.data,
          total: 1,
          success: true,
          message: backendData.message || `用户状态已${status === 1 ? '启用' : '禁用'}`
        };
      } else {
        throw new Error(backendData.message || '切换用户状态失败');
      }
    } catch (error) {
      console.error('切换用户状态失败:', error);
      throw new Error(error instanceof Error ? error.message : '切换用户状态失败');
    }
  }
};